﻿using System;
using System.Collections;
using System.Web.UI.WebControls;
using Autofac;
using ComputerVision.BaseForm;
using ComputerVision.Common;
using ComputerVision.Data;
using ComputerVision.PhieuDieuTraCoSoForm;
using ComputerVision.Services;
using ComputerVision.Services.User;
using QuanLyThongTinCoSo.Common;

namespace ComputerVision.NguyenNhanChayForm
{
    public partial class frmNguyenNhanChayDetail : frmDetail
    {
        private readonly IService<NguyenNhanChay> _nguyenNhanChayService;        
        private readonly IUserService<aspnet_Users> _userService;        

        public frmNguyenNhanChayDetail()
        {
            InitializeComponent();
            _nguyenNhanChayService = Program.Container.Resolve<IService<NguyenNhanChay>>();
            _userService = Program.Container.Resolve<IUserService<aspnet_Users>>();
            Text = @"Thêm mới nguyên nhân cháy";            
            txtTen.Focus();
        }        

        public frmNguyenNhanChayDetail(Guid id)
        {
            InitializeComponent();
            _nguyenNhanChayService = Program.Container.Resolve<IService<NguyenNhanChay>>();
            _userService = Program.Container.Resolve<IUserService<aspnet_Users>>();
            Text = @"Sửa nguyên nhân cháy";

            txtTen.Focus();

            _fromtype = Constants.TypeForm.Edit;
            guid = id;

            NguyenNhanChay item = _nguyenNhanChayService.Detail(id);
            if (item != null)
            {
                txtTen.Text = item.NguyenNhan;               
            }
        }        

        #region Validation

        protected override bool Validator()
        {
            bool flag = true;

            errorProvider.Dispose();
            
            if (string.IsNullOrEmpty(txtTen.Text))
            {
                errorProvider.SetError(txtTen, "Bạn chưa nhập tên nguyên nhân cháy. Xin vui lòng kiểm tra lại");
                flag = false;
            }

            return flag;
        }

        #endregion

        #region Insert
        protected override void Insert()
        {
            try
            {
                var model = new NguyenNhanChay
                {
                    Id = Guid.NewGuid(),
                    NguyenNhan = txtTen.Text
                };
                _nguyenNhanChayService.Create(model);
                
            }
            catch (Exception ex)
            {
                AlertList.Error("Lỗi phát sinh khi tạo mới dữ liệu.");
            }
        }
        #endregion

        #region Edit

        protected override void Edit()
        {
            var item = _nguyenNhanChayService.Detail(guid);
            if (item != null)
            {
                item.NguyenNhan = txtTen.Text;
                _nguyenNhanChayService.Update(item);
            }
        }

        #endregion
    }
}
